﻿using System;
using System.Drawing;

namespace FotoAlbum
{
    public class Thumbnail : IDisposable
    {
        public const int MAXIMUM_WIDTH = 160;
        public const int MAXIMUM_HEIGHT = 90;

        /// <summary>
        /// Get the path to the actual file.
        /// </summary>
        public string Path { get; private set; }

        /// <summary>
        /// The actual thumbnail image.
        /// </summary>
        public Image Image { get; private set; }
        //private object imageLock = new object();

        public Thumbnail(string path)
        {
            this.Path = path;
        }

        /// <summary>
        /// Release the system resources used by the image.
        /// </summary>
        public void Dispose()
        {
            //lock (imageLock)
            {
                if (Image != null)
                {
                    Image.Dispose();
                    Image = null;
                }
            }
        }

        /// <summary>
        /// Load the thumbnail.
        /// </summary>
        public void Load()
        {
            // Ensure the image is empty; we do not want to load it twice!
            if (Image != null)
                throw new InvalidOperationException("The image has already been loaded.");

            //lock (imageLock)
            {
                try
                {
                    using (Image temp = Image.FromFile(this.Path))
                    {
                        // Ensure we use the actual image; not a premade thumbnail. (MSDN)
                        temp.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        temp.RotateFlip(RotateFlipType.Rotate180FlipNone);

                        // Create the actual thumbnail.
                        Image = temp.GetThumbnailImage(MAXIMUM_WIDTH, MAXIMUM_HEIGHT, null, IntPtr.Zero);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.GetType().ToString() + ": " + ex.Message);
                }
            }
        }
    }
}
